package com.gsma.calendar.android.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

import com.gsma.calendar.android.R;
import com.gsma.calendar.android.adapter.GlobalEventAdapter;
import com.gsma.calendar.android.db.CalendarGSMAColumns;
import com.gsma.calendar.android.db.CalendarGsmaQuery;
import com.gsma.calendar.android.db.GlobalEventColumns;
import com.gsma.calendar.android.db.GlobalEventQuery;
import com.gsma.calendar.android.db.LocalCalendarEventsColumns;
import com.gsma.calendar.android.model.CalendarObject;
import com.gsma.calendar.android.model.GlobalEvent;
import com.gsma.calendar.android.model.LocalCalendarEvents;
import com.gsma.calendar.android.util.CalendarGsmaUtil;
import com.gsma.calendar.android.util.Config;
import com.gsma.calendar.android.util.ToastUtil;

public class GlobalEventsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
	private Spinner spinner;
	private ListView listView;
	private GlobalEventAdapter adapter;
	private Cursor cursorCalendar;
	public static final int UPDATE_CALENDAR = 1;
	private ProgressDialog progress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.global_event);

		spinner = (Spinner) findViewById(R.id.spinner);
		listView = (ListView) findViewById(R.id.list_global_events);
		listView.setOnItemClickListener(this);

		getSupportLoaderManager().initLoader(GlobalEventQuery._TOKEN, null, this);

		String[] projection = new String[] { "_id", "name" };
		String selection = "selected=1";
		String path = "calendars";

		CalendarGsmaUtil calen = new CalendarGsmaUtil(GlobalEventsActivity.this);
		cursorCalendar = calen.getCalendarManagedCursor(projection, selection, path);

		SimpleCursorAdapter calendarAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursorCalendar, new String[] { "name" },
				new int[] { android.R.id.text1 });

		spinner.setAdapter(calendarAdapter);
		calendarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		switch (id) {
		case GlobalEventQuery._TOKEN:
			return new CursorLoader(GlobalEventsActivity.this, GlobalEvent.CONTENT_URI, GlobalEventQuery.PROJECTION, null, null, GlobalEvent.START_TIME_SORT);
		default:
			return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case GlobalEventQuery._TOKEN:
			if (cursor != null && cursor.moveToFirst()) {
				startManagingCursor(cursor);
				adapter = new GlobalEventAdapter(GlobalEventsActivity.this, cursor);
				listView.setAdapter(adapter);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub

	}

	public void checkAll(View view) {
		ContentValues values = new ContentValues();
		values.put(GlobalEventColumns.ISCHECKED.getName(), 1);
		getContentResolver().update(GlobalEvent.CONTENT_URI, values, null, null);
		getSupportLoaderManager().destroyLoader(GlobalEventQuery._TOKEN);
		getSupportLoaderManager().initLoader(GlobalEventQuery._TOKEN, null, this);
	}

	public void unCheckAll(View view) {
		ContentValues values = new ContentValues();
		values.put(GlobalEventColumns.ISCHECKED.getName(), 0);
		getContentResolver().update(GlobalEvent.CONTENT_URI, values, null, null);
		getSupportLoaderManager().destroyLoader(GlobalEventQuery._TOKEN);
		getSupportLoaderManager().initLoader(GlobalEventQuery._TOKEN, null, this);
		adapter.getListChecked().clear();
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		Intent intent = new Intent(GlobalEventsActivity.this, GlobalEventDetail.class);
		String nameEvent = null;
		GlobalEventAdapter adapter = (GlobalEventAdapter) adapterView.getAdapter();
		Cursor cursor = adapter.getCursor();
		if (cursor != null && cursor.moveToPosition(position)) {
			nameEvent = cursor.getString(GlobalEventQuery.EVENT);
		}
		intent.putExtra(Config.EVENT, nameEvent);
		startActivity(intent);
	}

	public void addChecked(View view) {

		CalendarGsmaUtil calendar = new CalendarGsmaUtil(GlobalEventsActivity.this);
		long calendarId = spinner.getSelectedItemId();
		if (adapter != null) {
			ArrayList<String> list = adapter.getListChecked();
			progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
			UpdateCalendar updateCalendar = new UpdateCalendar(list, calendarId, calendar, GlobalEventsActivity.this);
			updateCalendar.run();
		}
	}

	private class UpdateCalendar implements Runnable {
		private ArrayList<String> list;
		private long calendarId;
		private CalendarGsmaUtil calendar;
		private Context context;

		public UpdateCalendar(ArrayList<String> list, long calendarId, CalendarGsmaUtil calendar, Context context) {
			this.list = list;
			this.calendarId = calendarId;
			this.calendar = calendar;
			this.context = context;
		}

		@Override
		public void run() {
			for (int i = 0; i < list.size(); i++) {
				String global_event = list.get(i);

				Uri uri = CalendarObject.CONTENT_URI.buildUpon().appendPath("*").build();
				String[] projection = new String[] { CalendarGSMAColumns._ID.getName(), CalendarGSMAColumns.END_TIME.getName(),
						CalendarGSMAColumns.EVENT.getName(), CalendarGSMAColumns.EVENT_TYPE.getName(), CalendarGSMAColumns.SESSION.getName(),
						CalendarGSMAColumns.SPEAKERS.getName(), CalendarGSMAColumns.START_TIME.getName(), CalendarGSMAColumns.TAG.getName(),
						CalendarGSMAColumns.WHERE.getName(), LocalCalendarEventsColumns.SESSION_NAME.getName(),
						LocalCalendarEventsColumns.CALENDAR_ID.getName(), LocalCalendarEventsColumns.URI_EVENT.getName() };

				List<String> list_of_exist = new ArrayList<String>();
				Cursor cursor_of_existed = context.getContentResolver().query(
						uri,
						projection,
						LocalCalendarEventsColumns.CALENDAR_ID.getName() + " = " + calendarId + " AND " + CalendarGSMAColumns.EVENT.getName() + " = '"
								+ global_event + "'", null, null);
				if (cursor_of_existed != null && cursor_of_existed.moveToFirst()) {
					do {
						String exist_session = cursor_of_existed.getString(cursor_of_existed.getColumnIndex(LocalCalendarEventsColumns.SESSION_NAME.getName()));
						list_of_exist.add(exist_session);
					} while (cursor_of_existed.moveToNext());
				}
				cursor_of_existed.close();
				// /////////////////////////////////////////////////////////////////////////////////
				Cursor cursor_of_all = context.getContentResolver().query(CalendarObject.CONTENT_URI, CalendarGsmaQuery.PROJECTION,
						CalendarGSMAColumns.EVENT.getName() + " = '" + global_event + "'", null, null);
				if (cursor_of_all != null && cursor_of_all.moveToFirst()) {
					do {
						String session = cursor_of_all.getString(CalendarGsmaQuery.SESSION);
						if (!list_of_exist.contains(session)) {
							Uri uri_insert = calendar.makeNewCalendarEntry((int) calendarId, cursor_of_all);
							ContentValues contentValues = new ContentValues();
							contentValues.put(LocalCalendarEventsColumns.CALENDAR_ID.getName(), calendarId);
							contentValues.put(LocalCalendarEventsColumns.URI_EVENT.getName(), uri_insert.toString());
							contentValues.put(LocalCalendarEventsColumns.SESSION_NAME.getName(), session);
							getContentResolver().insert(LocalCalendarEvents.CONTENT_URI, contentValues);
						}
					} while (cursor_of_all.moveToNext());
					cursor_of_all.close();
				}
			}
			handler.sendEmptyMessage(UPDATE_CALENDAR);
		}

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATE_CALENDAR:
				if (progress != null)
					progress.dismiss();
				ToastUtil.showText(GlobalEventsActivity.this, getString(R.string.event_were_added));
				break;

			}
		};
	};

}